<template>
  <!-- 个人信息页面 -->
  <div>
    <van-cell-group inset>
      <!-- 输入任意文本 -->
      <van-field v-model.trim="nickname" label="网名" placeholder="网名"/>
      <van-field v-model.trim="email" type="email" label="邮箱" placeholder="邮箱"/>
      <van-field v-model.trim="phone" type="number" label="电话" placeholder="电话"/>
    </van-cell-group>
    <button @click="submit" class="submit">提交</button>
  </div>
</template>

<script>
import qs from 'qs'
import { mapState } from 'vuex'

export default {
  data () {
    return {
      nickname: '',
      email: '',
      reg: '',
      res: '',
      tocken: '',
      id: 0,
      phone: 0
    }
  },
  computed: {
    ...mapState(['tokenInfo'])
  },
  methods: {
    submit () {
      // 邮箱验证规则
      this.reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      this.res = this.reg.test(this.email)
      // console.log(this.res)
      if (this.res) {
        // console.log(this.email)
        this.id = this.$route.query.id
        this.updateUserInfo(this.tokenInfo)
      } else {
        this.$toast('邮箱错误')
      }
    },
    // 更新用户信息
    async updateUserInfo (token) {
      const { data: res } = await this.$http({
        url: '/my/userinfo',
        method: 'POST',
        headers: {
          'Access-Control-Allow-Origin': '*', // 解决cors头问题
          'Access-Control-Allow-Credentials': 'true', // 解决session问题
          Authorization: token
        },
        data: qs.stringify({ nickname: this.nickname, email: this.email, id: this.id, phone: this.phone })
      })
      // console.log(res)
      if (res.status !== 1) {
        this.$toast(res.message)
      } else {
        this.$toast(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.submit{
  width: 50%;
  height: 50px;
  background-color: blue;
  display:block;
  margin:0 auto;
}
</style>
